package service

import (
	"errors"

	// "GinAdmin/internal/model"
	// "GinAdmin/pkg/database"
	"GinAdmin/core/database"
	"GinAdmin/model"

	"gorm.io/gorm"
)

// SettingService 设置服务
type SettingService struct{}

// GetSetting 获取设置
func (s *SettingService) GetSetting(key string) (*model.Setting, error) {
	var setting model.Setting
	if err := database.DB.Where("key = ?", key).First(&setting).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("设置不存在")
		}
		return nil, err
	}
	return &setting, nil
}

// CreateSetting 创建设置
func (s *SettingService) CreateSetting(req *model.CreateSettingRequest) (*model.Setting, error) {
	var count int64
	database.DB.Model(&model.Setting{}).Where("key = ?", req.Key).Count(&count)
	if count > 0 {
		return nil, errors.New("设置键已存在")
	}

	setting := model.Setting{
		Key:    req.Key,
		Value:  req.Value,
		Group:  req.Group,
		Remark: req.Remark,
		Type:   req.Type,
	}

	if err := database.DB.Create(&setting).Error; err != nil {
		return nil, err
	}

	return &setting, nil
}

// UpdateSetting 更新设置
func (s *SettingService) UpdateSetting(key string, req *model.UpdateSettingRequest) (*model.Setting, error) {
	var setting model.Setting
	if err := database.DB.Where("key = ?", key).First(&setting).Error; err != nil {
		return nil, err
	}

	updates := map[string]interface{}{
		"value": req.Value,
	}

	if req.Group != "" {
		updates["group"] = req.Group
	}

	if req.Remark != "" {
		updates["remark"] = req.Remark
	}

	if req.Type != "" {
		updates["type"] = req.Type
	}

	if err := database.DB.Model(&setting).Updates(updates).Error; err != nil {
		return nil, err
	}

	return &setting, nil
}

// DeleteSetting 删除设置
func (s *SettingService) DeleteSetting(key string) error {
	var setting model.Setting
	if err := database.DB.Where("key = ?", key).First(&setting).Error; err != nil {
		return err
	}

	if err := database.DB.Delete(&setting).Error; err != nil {
		return err
	}

	return nil
}

// GetSettingsByGroup 根据分组获取设置
func (s *SettingService) GetSettingsByGroup(group string) ([]model.Setting, error) {
	var settings []model.Setting
	query := database.DB.Model(&model.Setting{})

	if group != "" {
		query = query.Where("group = ?", group)
	}

	if err := query.Order("id ASC").Find(&settings).Error; err != nil {
		return nil, err
	}

	return settings, nil
}

// BatchUpdateSettings 批量更新设置
func (s *SettingService) BatchUpdateSettings(req *model.BatchUpdateSettingsRequest) error {
	// 开启事务
	tx := database.DB.Begin()

	for _, item := range req.Settings {
		var setting model.Setting
		if err := tx.Where("key = ?", item.Key).First(&setting).Error; err != nil {
			tx.Rollback()
			return err
		}

		if err := tx.Model(&setting).Update("value", item.Value).Error; err != nil {
			tx.Rollback()
			return err
		}
	}

	tx.Commit()
	return nil
}
